
package com.nd.qa.shareplate.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nd.qa.shareplate.common.CPResultCode;
import com.nd.qa.shareplate.common.MD5;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.model.Project;
import com.nd.qa.shareplate.model.User;
import com.nd.qa.shareplate.service.LoginService;
import com.nd.qa.shareplate.service.ProjectService;
import com.nd.qa.shareplate.service.UserService;
import com.nd.qa.shareplate.util.JsonUtil;


/**
 * <p>用户登录信息类</p>
 * @author huangjian
 * @createDate 2015-08-31 下午 17:36:36
 * @version V1.0
 */
@Controller("com.nd.qa.shareplate.controller.LoginController")
@RequestMapping("/user/*")
public class LoginController { 
	
	private static Logger log = LoggerFactory.getLogger(LoginController.class.getName());
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.LoginService")
	private LoginService loginService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.UserService")
	private UserService userService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ProjectService")
	private ProjectService projectService;
	
	/**
	 * 用户访问首页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model){
		try {
			log.info("request.getScheme()="+request.getScheme()+",request.getRemoteAddr()="+request.getRemoteAddr()+","+InetAddress.getLocalHost().getHostAddress());
			List<HashMap<String, Object>> menuList= loginService.queryHeaderMenuFunction();
			model.addAttribute("menuList", menuList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/main/index";
	}
	/**
	 * 用户登录界面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response,Model model){
		/*User user = new User();
		user.setUserId("1");
		Map<String, Object> user2 = loginService.queryUserById(user);*/
		try {
			List<HashMap<String, Object>> menuList= loginService.queryHeaderMenuFunction();
			model.addAttribute("menuList", menuList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/main/login";
	}
	/**
	 * 用户登录验证
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryUserById")
	@ResponseBody
	public void queryUserById(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session,Model model){
		
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		try {
			if (params==null) {
				resultMap.put("code", "-1");
				resultMap.put("errorsList", "入参为空");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
			String userName = String.valueOf(param.get("userName"));
			if (userName==null||userName=="") {
				resultMap.put("code", "-1");
				resultMap.put("errorsList", "用户名为空");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			String userPassword = String.valueOf(param.get("userPassword"));
			if (userPassword==null||userPassword=="") {
				resultMap.put("code", "-1");
				resultMap.put("errorsList", "用户密码为空");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			//用户密码加密
			userPassword = MD5.GetMD5Code(userPassword);
			param.put("userName", userName);
			param.put("userPassword", userPassword);
			HashMap<String, Object> returnMap = loginService.queryUserById(param);
			//保存用户信息到session中
			if(CPResultCode.CP0000.equals(returnMap.get("code"))){
				//查询用户权限
				/*HashMap<String, Object> map  = new HashMap<String,Object>();
				map.put("userId", String.valueOf(returnMap.get("user_id")));
				List<HashMap<String, Object>> roleList = loginService.queryUserRoleById(map);
				StringBuffer roleIds = new StringBuffer();
				for (int i = 0; i < roleList.size(); i++) {
					HashMap<String, Object> roleMap = roleList.get(i);
					if (i==roleList.size()-1) {
						roleIds.append(String.valueOf(roleMap.get("role_id")));
					}else {
						roleIds.append(String.valueOf(roleMap.get("role_id"))+",");
					}
				}*/
				SessionUserInfo sessionCustInfo = new SessionUserInfo();
				sessionCustInfo.setUserId(String.valueOf(returnMap.get("user_id")));
				sessionCustInfo.setUserName(userName);
				//sessionCustInfo.setRoleIds(roleIds.toString());
				session.setAttribute(SysConstant.SESSION_KEY_LOGIN_USER, sessionCustInfo);
				resultMap.put("code", "0");
				resultMap.put("data", sessionCustInfo);
			}else{
				resultMap.put("code", "-1");
				resultMap.put("errorsList", String.valueOf(returnMap.get("message")));
			}
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			log.error(e.toString());
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 用户登录后的首页
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/home")
	public String goHome(HttpSession session,HttpServletRequest request,HttpServletResponse response,Model model){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		try {
			log.info("request.getScheme()="+request.getScheme()+",request.getRemoteAddr()="+request.getRemoteAddr()+","+InetAddress.getLocalHost().getHostAddress());
			if (sessionUserInfo==null||"".equals(sessionUserInfo)) {
				//查询头部菜单
				List<HashMap<String, Object>> menuList = loginService.queryHeaderMenuFunction();
				model.addAttribute("menuList", menuList);
				return "/main/login";
			}
			//查询头部菜单
			List<HashMap<String, Object>> menuList = loginService.queryHeaderMenuFunction();
			model.addAttribute("menuList", menuList);
			model.addAttribute("userId", sessionUserInfo.getUserId());
			//默认查询所有的项目
			Project project = new Project();
			project.setUserId(sessionUserInfo.getUserId());
			Integer totalPages = 0;//总记录数
			Integer currentPage = 1;
			Integer pageSize = 8;
			Integer startSize = (currentPage-1)*pageSize;
			project.setUserId(sessionUserInfo.getUserId());
			List<HashMap<String, Object>> totalProList = projectService.queryTotalProject(project);
			if (totalProList.size()>0) {
				if (totalProList.size()%pageSize==0) {
					totalPages = totalProList.size()/pageSize;
				}else {
					totalPages = totalProList.size()/pageSize + 1;
				}
			}
			HashMap<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("startSize", startSize);
			paramMap.put("pageSize", pageSize);
			paramMap.put("userId", sessionUserInfo.getUserId());
			List<HashMap<String, Object>> projectList = projectService.queryLimitProject(paramMap);
			for (int i = 0; i < projectList.size(); i++) {
				HashMap<String, Object> prjMap = projectList.get(i);
				//URLDecoder.decode(String.valueOf(prjMap.get("ci_report_url")),"UTF-8");
				URLEncoder.encode(String.valueOf(prjMap.get("ci_report_url")),"UTF-8");
			}
			model.addAttribute("projectList", projectList);
			model.addAttribute("totalPages", totalPages);
			HashMap<String, Object> reMap = new HashMap<String,Object>();
			reMap.put("userName", sessionUserInfo.getUserName());
			reMap.put("userId", sessionUserInfo.getUserId());
			reMap.put("roleIds", sessionUserInfo.getRoleIds());
			model.addAttribute("adminUserName", sessionUserInfo.getUserName());
			model.addAttribute("data", JsonUtil.toString(reMap));
		} catch (Exception e) {
			log.error("异常信息"+e);
			e.printStackTrace();
		}
		return "/main/home";
	}
	@SuppressWarnings("unchecked")
	/**
	 * 注册用户
	 * @param session
	 * @param request
	 * @param response
	 * @param params
	 */
	@RequestMapping("/registerUser")
	public void registerUser(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
		
		HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		try {
			String userName = String.valueOf(param.get("userName"));
			if (userName==null||userName=="") {
				resultMap.put("code", "-1");
				resultMap.put("message", "用户名为空");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			String userPassword = String.valueOf(param.get("userPwd"));
			if (userPassword==null||userPassword=="") {
				resultMap.put("code", "-1");
				resultMap.put("message", "用户密码为空");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss");
			String createTime = simpleDateFormat.format(new Date());
			String userTime = simpleDate.format(new Date());
			String userId= userName;
			//用户密码加密
			userPassword = MD5.GetMD5Code(userPassword);
			User user = new User();
			user.setUserName(userName);
			user.setUserPassword(userPassword);
			user.setUserId(userId);
			user.setCreateTime(createTime);
			user.setStatus("A");
			HashMap<String, Object> returnMap = userService.registerUser(user);
			if (CPResultCode.CP0000.equals(String.valueOf(returnMap.get("code")))) {
				resultMap.put("code", "0");
				resultMap.put("message", "注册成功");
			}else {
				resultMap.put("code", "-1");
				resultMap.put("message", returnMap.get("message"));
			}
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			log.error("异常信息"+e);
			e.printStackTrace();
		}
	}
	/**
	 * 注销用户
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request,HttpServletResponse response,Model model){
		
		HttpSession session = request.getSession(false);//防止创建Session
		if(session == null){
			return "/main/login";
		}
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		try {
			List<HashMap<String, Object>> menuList= loginService.queryHeaderMenuFunction();
			model.addAttribute("menuList", menuList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.removeAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		//model.addAttribute("userId", sessionUserInfo.getUserId());
		return "/main/login";
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param params
	 * @return
	 */
	@RequestMapping("/queryByUserName")
	public void queryByUserName(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
		
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String userName = params;
			User user = new User();
			try {
				user = userService.queryByUserName(userName);
			} catch (Exception e) {
				e.printStackTrace();
			}
			resultMap.put("user", user);
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param params
	 * @return
	 */
	@RequestMapping("/update")
	public void update(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		try {
			String userName = params;
			User user = new User();
			try {
				user = userService.queryByUserName(userName);
			} catch (Exception e) {
				e.printStackTrace();
			}
			resultMap.put("user", user);
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 修改用户信息
	 * @param request
	 * @param response
	 * @param params
	 * @return
	 */
	@RequestMapping("/updateUser")
	public void updateUser(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		String userId = sessionUserInfo.getUserId();
		response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		String oldUserPwd = String.valueOf(param .get("oldUserPwd"));
		String newUserPwd = String.valueOf(param.get("newUserPwd"));
		String oldMD5 = MD5.GetMD5Code(oldUserPwd);
		String newMD5 = MD5.GetMD5Code(newUserPwd);
		try {
			User user = new User();
			try {
				user = userService.queryByUserById(userId);
				if (oldMD5.equals(user.getUserPassword())) {
					user.setUserPassword(newMD5);
					userService.updateUser(user);
				}else{
					resultMap.put("code", "-1");
					resultMap.put("message", "原密码不正确，请重新输入!");
					response.getWriter().print(JsonUtil.toString(resultMap));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			resultMap.put("code", "0");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
